var ds; // debugging

// IE FIX
if (!Array.prototype.filter){
  Array.prototype.filter = function(fun /*, thisp*/){
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++){
      if (i in this){
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}  

var PIR = { 
init: function() {
    var fm = Ext.form;
    var ps = 60;

    Ext.QuickTips.init();

    // create the Data Store
    ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/pir/json/'
        }),
        reader: new Ext.data.JsonReader({
            root: 'items',
            id: 'pk',
            totalProperty: 'totalCount'
        }, [
	    {name: 'name', mapping: 'fields.name' },
            {name: 'length', mapping: 'fields.length', type: 'int' },
            {name: 'type', mapping: 'fields.type' },
            {name: 'status', mapping: 'fields.status' },
            {name: 'source', mapping: 'fields.source' },
            {name: 'common', mapping: 'fields.common' },
            {name: 'formal', mapping: 'fields.formal' }
        ]),

        // turn on remote sorting
        remoteSort: true
    });
    ds.setDefaultSort('name', 'desc');

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Name",
           dataIndex: 'name',
           width: 275,
           //renderer: renderTopicPlain,
           css: 'white-space:normal;'
        },{
           header: "Length",
           dataIndex: 'length',
           width: 50,
           align: 'right'
        },{
           header: "Type",
           dataIndex: 'type',
           width: 100,
           hidden: false
        },{
           id: 'status',
           header: "Status",
           dataIndex: 'status',
           //renderer: renderLastPlain,
           width: 100
        },{
           header: "Source",
           dataIndex: 'source',
           width: 90,
           hidden: false
        },{
           header: "Common",
           dataIndex: 'common',
           width: 80,
           hidden: false
        },{
           header: "Formal",
           dataIndex: 'formal',
           width: 80,
           hidden: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    // create the editor grid
    var grid = new Ext.grid.Grid('topic-grid', {
        ds: ds,
        cm: cm,
        selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
        enableColLock: false,
	loadMask: true
    });

    // make the grid resizable, do before render for better performance
    var rz = new Ext.Resizable('topic-grid', {
        wrap:true,
        minHeight:100,
        pinned:true,
        handles: 's'
    });
    rz.on('resize', grid.autoSize, grid);

    // render it
    grid.render();

    var gridFoot = grid.getView().getFooterPanel(true);

    // add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: ps,
        displayInfo: true,
        displayMsg: 'Displaying Protein Sequences {0} - {1} of {2}',
        emptyMsg: "No Protein Sequences to display"
    });

    var gridHead = grid.getView().getHeaderPanel();
    gridHead.show();
    var tb = new Ext.Toolbar(gridHead);
    var filterMenuItems = [
	'<b class="menu-title">Filter Columns</b>',
	new Ext.menu.CheckItem({ text: 'Name', checked: true, group: 'filter' }),
	new Ext.menu.CheckItem({ text: 'Source', checked: false, group: 'filter' }),
	new Ext.menu.CheckItem({ text: 'Common', checked: false, group: 'filter' }),
	new Ext.menu.CheckItem({ text: 'Formal', checked: false, group: 'filter' })
    ];
    var filterMenu = new Ext.menu.Menu({
	id: 'filterMenu',
	items: filterMenuItems
    });
    tb.add({
	text: 'Server side name filter',
	tooltip: 'Filters data getting into the grid from the server side.',
	icon: '/static/m.png',
	cls: 'x-btn-text-icon btn-search-icon',
	menu: filterMenu
    });
/*    var sf = new Ext.ux.SearchField({
	paramName: 'filter_name',
	columnParamValueLowerCase: true,
	columnParamName: 'filter_col',
	columnMenu: filterMenu,
	emptyText: 'Type to filter',
	store: ds
    });
    tb.add(sf);*/
// /*    
    var sstb = tb.addDom({
	tag: 'input',
	id: 'ssfilter',
	type: 'text',
	size: 30,
	value: '',
	style: 'background: #F0F0F9;'
    });
    var sstblabel = tb.addDom({
	tag: 'div',
	id: 'ssfilterlabel'
    });
// */
    var filterStore = new Ext.data.SimpleStore({
        fields: ['query'],
	data: []
    });
    var ssFilterBox = new Ext.form.HistoryComboBox({
	emptyText: "No filter",
//	triggerAction: "query",
//	typeAhead: false,
	dummyData: true
    });
    ssFilterBox.applyTo('ssfilter');

    tb.addSeparator();

    var quickMenuItems = [
	'<b class="menu-title">Quicksearch Columns</b>',
	new Ext.menu.CheckItem({ text: 'Name', hideOnClick: false, checked: true }),
	new Ext.menu.CheckItem({ text: 'Length', hideOnClick: false, checked: false }),
	new Ext.menu.CheckItem({ text: 'Type', hideOnClick: false, checked: false }),
	new Ext.menu.CheckItem({ text: 'Status', hideOnClick: false, checked: true }),
	new Ext.menu.CheckItem({ text: 'Source', hideOnClick: false, checked: true }),
	new Ext.menu.CheckItem({ text: 'Common', hideOnClick: false, checked: true }),
	new Ext.menu.CheckItem({ text: 'Formal', hideOnClick: false, checked: true })
    ];
    var quickMenu = new Ext.menu.Menu({
	id: 'quickMenu',
	items: quickMenuItems
    });
    tb.add({
	text: 'Quicksearch',
	tooltip: 'Quickly search through the current page.',
	icon: '/static/m.png',
	cls: 'x-btn-text-icon btn-search-icon',
	menu: quickMenu
    });
/*    var qsf = new Ext.ux.SearchField({
	columnParamValueLowerCase: true,
	columnParamName: 'filter_col',
	columnMenu: filterMenu,
	emptyText: 'Type to quicksearch',
	quickFilter: true,
	store: ds
    });
    tb.add(qsf);*/
//    /*
    var quicksearch = tb.addDom({
	tag: 'input',
	id: 'quicksearch',
	type: 'text',
	size: 30,
	value: '',
	style: 'background: #F0F0F9;'
    });
    var searchBox = new Ext.form.HistoryComboBox({
	hideTrigger: true,
	emptyText: "Type to quicksearch",
	//rememberOn: 'all'
	rememberOn: 'delay'
    });
    searchBox.applyTo('quicksearch');

    var searchRec = Ext.data.Record.create([
        {name: 'query', type: 'string'}
    ]);
    var onFilteringBeforeQuery = function(e) {
	//grid.getSelectionModel().clearSelections();
	var value = searchBox.getValue();
        if (value.length==0) {
            ds.clearFilter();
        } else {
            value = value.replace(/^\s+|\s+$/g, "");
            if (value=="")
                return;
            ds.filterBy(function(r) {
		// filter operator AND on all keywords for defined columns
                valueArr = value.split(/\ +/);
		for (var j=0; j<valueArr.length; j++) {
		    re = new RegExp(Ext.escapeRe(valueArr[j]), "i");
		    keep = false;
		    for (var i=0,items=quickMenuItems,len=items.length; i<len; i++){
            	        if (items[i].checked) {
			    if (re.test(r.data[items[i].text.toLowerCase()])==true){
			        keep = true;
			    }
			}
		    }
		    if (!keep){
			return false;
		    }
		}
		return true;
            });
        }
    };
    quickMenu.on('click', onFilteringBeforeQuery);
    searchBox.on("valueChange", onFilteringBeforeQuery);
    ssFilterBox.on("valueChange", function(e) {
	var filterCol = filterMenuItems.filter(function(element, index, array) {
	    return element.checked;
	})[0].text;
	var value = ssFilterBox.getValue();
	if ((!value || value=='') && !ds.baseParams['filter_name']) {
	    return;
	} else if (value.length>0) {
	    ds.baseParams = {"filter_col":filterCol,"filter_name":value};
	    Ext.get('ssfilterlabel').update("- filter on "+value);
	} else {
	    ds.baseParams = {};
	    Ext.get('ssfilterlabel').update("");
	}
	paging.cursor = 0; // reset cursor on new filter
	ds.load({params:{start: paging.cursor, limit: paging.pageSize}});
    });
//    */

    // trigger the data store load
    ds.load({params:{start:0, limit:ps}});
    
    var converted = new Ext.form.ClearableComboBox({
	hideClearButton: false,
	hideTrigger: false,
	typeAhead: true,
	triggerAction: 'all',
	transform: 'state',
	width: 135,
	forceSelection: false
    });
}};

Ext.onReady(PIR.init, PIR);
